-module( gameWorld ).
-export( [start/0, addUserSync/3] ).


-record( gameWorld, { nextId=1, objects=[] } ).


start() ->
  spawn( fun() -> startLoop() end ).
  
  
addUserSync( World, ClientObjectPid, Login ) -> 
  World ! { add_user, self(), ClientObjectPid, Login },
  receive
    { user_added, ClientId } -> ClientId
  end.



startLoop() ->
  loop( #gameWorld{} ).

  

loop( State ) ->
  receive
    { add_user, SrcPid, ClientObjectPid, Login } ->
      Id = State#gameWorld.nextId,
      error_logger:info_msg( "Adding client ~p with login ~p from ~p\n", [Id, Login, SrcPid] ),
      SrcPid ! { user_added, Id },
      loop( State#gameWorld{ objects = [ ClientObjectPid | State#gameWorld.objects ], nextId = ( Id + 1 ) } );

    { game_broadcast, Msg } ->
      [ Pid ! Msg || Pid <- State#gameWorld.objects ], %%naive
      loop( State ); 

    Other ->
      error_logger:error_msg( "GameWorld: Unknown message ~p", [Other] ),
      loop( State )
  end.
